<template>
  <a-modal
    :destroy-on-close="true"
    :mask-closable="false"
    title="角色用户管理"
    :width="1200"
    :open="visible"
    :onCancel="onCancel"
    :footer="null"
  >
    <!-- <template #footer>
        </template> -->
    <a-card
      :bordered="false"
      style="margin-bottom: 15px"
      :bodyStyle="{ paddingBottom: '0' }"
    >
      <a-form :labelCol="{ span: 6, offset: 0 }" :wrapper-col="{ span: 18 }">
        <a-row :gutter="16" justify="end">
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <a-form-item label="用户姓名：">
              <a-input
                placeholder="请输入"
                v-model:value="searchModelRef.username"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <a-form-item label="域账号：">
              <a-input
                placeholder="请输入"
                v-model:value="searchModelRef.adAccount"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <a-form-item label="科室：">
              <a-input
                placeholder="请输入"
                v-model:value="searchModelRef.orgName"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <div class="text-align-right" style="padding-bottom: 24px">
              <a-button type="primary" @click="searchFormSubmit">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchResetFields"
                >重置</a-button
              >
            </div>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <template #extra>
        <a-space>
          <a-button
            type="primary"
            danger
            v-if="data.length > 0"
            @click="() => deleteAlls()"
            >全部删除</a-button
          >
          <a-button type="primary" @click="() => addUser()">添加用户</a-button>
        </a-space>
      </template>
      <a-table
        :rowKey="(record) => record.id"
        :columns="columns"
        :data-source="data"
        :loading="loading"
        :row-selection="rowSelection"
        :pagination="{
          ...pagination,
          onChange: (page) => {
            getUserList(page);
          },
        }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button
              type="link"
              @click="() => deleteSelectedUser(record.id)"
              class="delete-button"
              >删除</a-button
            >
          </template>
        </template>
      </a-table>
    </a-card>
  </a-modal>
  <a-modal
    :destroy-on-close="true"
    :mask-closable="false"
    title="角色用户管理"
    :width="1200"
    :open="addUserDialog"
    :onCancel="() => (addUserDialog = false)"
  >
    <template #footer>
      <a-button key="back" @click="() => (addUserDialog = false)"
        >取消</a-button
      >
      <a-button key="submit" type="primary" @click="() => confirmAdd()"
        >确定</a-button
      >
    </template>
    <a-card
      :bordered="false"
      style="margin-bottom: 15px"
      :bodyStyle="{ paddingBottom: '0' }"
    >
      <a-form :labelCol="{ span: 6, offset: 0 }" :wrapper-col="{ span: 18 }">
        <a-row :gutter="16" justify="end">
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <a-form-item label="用户姓名：">
              <a-input
                placeholder="请输入"
                v-model:value="searchAllModelRef.username"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <a-form-item label="域账号：">
              <a-input
                placeholder="请输入"
                v-model:value="searchAllModelRef.adAccount"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <a-form-item label="科室：">
              <a-input
                placeholder="请输入"
                v-model:value="searchAllModelRef.orgName"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <div class="text-align-right" style="padding-bottom: 24px">
              <a-button type="primary" @click="getUserAllList(1)"
                >查询</a-button
              >
              <a-button style="margin-left: 8px" @click="searchResetAllFields"
                >重置</a-button
              >
            </div>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <template #extra>
        <span>新增选项</span
        ><span style="color: red">{{ selectedUserRowIds.length }} </span
        ><span>人</span>
      </template>
      <a-table
        :rowKey="(record) => record.id"
        :columns="userColumns"
        :data-source="userAlldata"
        :loading="userLoading"
        :row-selection="rowSelectionUser"
        :pagination="{
          ...paginationUser,
          onChange: (page) => {
            getUserAllList(page);
          },
        }"
      />
    </a-card>
  </a-modal>
</template>
<script lang="ts" setup>
import { message } from "ant-design-vue";
import { defineProps, ref, watch } from "vue";
import {
  queryRelateUserList,
  deleteSelectedUsers,
  addSelectedUsers,
} from "../service";
import { queryUserList } from "@/views/userManager/service";
const props = defineProps<{
  roleId: number | string | undefined;
  visible: boolean;
  onCancel: Function;
}>();
const searchModelRef = ref({
  username: "",
  adAccount: "",
  orgName: "",
});
const searchAllModelRef = ref({
  username: "",
  adAccount: "",
  orgName: "",
});
const addUserDialog = ref(false);
const addUser = () => {
  addUserDialog.value = true;
  getUserAllList(1);
};
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      getUserList(1);
    }
  },
  { deep: true, immediate: true }
);
const columns = [
  {
    title: "用户姓名",
    dataIndex: "username",
    key: "username",
  },
  {
    title: "域账号",
    dataIndex: "adAccount",
    key: "email",
  },
  {
    title: "科室",
    dataIndex: "orgName",
    key: "orgName",
  },
  {
    title: "授权时间",
    dataIndex: "updatedTime",
    key: "updatedTime",
  },
  {
    title: "最近登录时间",
    dataIndex: "lastLoginTime",
    key: "lastLoginTime",
  },
  {
    title: "操作",
    key: "action",
  },
];
const userColumns = [
  {
    title: "用户姓名",
    dataIndex: "username",
    key: "username",
  },
  {
    title: "域账号",
    dataIndex: "adAccount",
    key: "email",
  },
  {
    title: "科室",
    dataIndex: "orgName",
    key: "orgName",
  },
];
const data = ref([]);
const userAlldata = ref([]);
const userLoading = ref(false);
const getUserAllList = async (current: number) => {
  const params = {
    pageNum: current,
    pageSize: paginationUser.value.pageSize,
    enableStatus: "1",
    ...searchAllModelRef.value,
  };
  userLoading.value = true;
  const res = await queryUserList(params);
  if (res.success) {
    userAlldata.value = res.data.records;
    paginationUser.value.total = res.data.total;
  }
  userLoading.value = false;
};
const confirmAdd = async () => {
  if (selectedUserRowIds.value.length <= 0) {
    message.error("请选择选项");
    return;
  }
  const req = {
    roleId: props.roleId,
    userIdList: selectedUserRowIds.value,
  };
  const res = await addSelectedUsers(req);
  if (res.success) {
    message.success("添加成功");
    addUserDialog.value = false;
    getUserList(1);
  }
};
// 列表分页
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0, // 假设总共有100条数据
  showTotal: (total) => `共 ${total} 条数据`,
  onChange: (page, pageSize) => {
    // 分页改变时的回调函数
    pagination.value.current = page;
    pagination.value.pageSize = pageSize;
    getUserList(page);
  },
  showSizeChanger: true,
  showQuickJumper: true,
});

// 列表分页
const paginationUser = ref({
  current: 1,
  pageSize: 10,
  total: 0, // 假设总共有100条数据
  showTotal: (total) => `共 ${total} 条数据`,
  onChange: (page, pageSize) => {
    // 分页改变时的回调函数
    pagination.value.current = page;
    pagination.value.pageSize = pageSize;
    getUserList(page);
  },
  showSizeChanger: true,
  showQuickJumper: true,
});

const loading = ref(false);
const selectedRowIds = ref([]);

const getUserList = async (current: number) => {
  const params = {
    pageNum: current,
    pageSize: pagination.value.pageSize,
    roleId: props.roleId,
    enableStatus: "1",
    ...searchModelRef.value,
  };
  loading.value = true;
  const res = await queryRelateUserList(params);
  if (res.success) {
    loading.value = false;
    data.value = res.data.records;
    selectedRowIds.value = res.data.records.map((record) => record.id);
    pagination.value.total = res.data.total;
  }
};
// 全选删除
const deleteAlls = async () => {
  if (selectedRowIds.value.length <= 0) {
    message.error("请选择选项");
    return;
  }
  const req = {
    roleId: props.roleId,
    userIdList: selectedRowIds.value,
  };
  const res = await deleteSelectedUsers(req);
  if (res.success) {
    message.success("删除关联用户成功");
    getUserList(1);
  }
};
// 删除选中的用户
const deleteSelectedUser = async (id) => {
  const req = {
    roleId: props.roleId,
    userIdList: [id],
  };
  const res = await deleteSelectedUsers(req);
  if (res.success) {
    message.success("删除关联用户成功");
    getUserList(1);
  }
};
// 搜索
const searchFormSubmit = async () => {
  getUserList(1);
};
const searchResetFields = async () => {
  searchModelRef.value = {
    username: "",
    adAccount: "",
    orgName: "",
  };
  searchFormSubmit();
};
const searchResetAllFields = async () => {
  searchAllModelRef.value = {
    username: "",
    adAccount: "",
    orgName: "",
  };
  getUserAllList(1);
};
const rowSelection = ref({
  onChange: (selectedRowKeys: [], selectedRows: []) => {
    selectedRowIds.value = selectedRowKeys;
  },
  selectedRowKeys: selectedRowIds,
  onSelectAll: (selected: boolean, selectedRows: [], changeRows: []) => {
    console.log(selected, selectedRows, changeRows);
  },
});

const selectedUserRowIds = ref([]);
const rowSelectionUser = ref({
  onChange: (selectedRowKeys: [], selectedRows: []) => {
    selectedUserRowIds.value = selectedRowKeys;
  },
  onSelectAll: (selected: boolean, selectedRows: [], changeRows: []) => {
    console.log(selected, selectedRows, changeRows);
  },
});
</script>
<style scoped lang="less">
.first {
  :deep(.ant-modal-footer) {
    display: none;
  }
}
</style>
